#include <48func.h>
int main(int argc, char *argv[])
{
    // ./5_homework_A 1.pipe 2.pipe
    ARGS_CHECK(argc,3);
    int fdr = open(argv[1],O_RDONLY);
    ERROR_CHECK(fdr,-1,"open fdr");
    int fdw = open(argv[2],O_WRONLY);
    ERROR_CHECK(fdw,-1,"open fdw");
    printf("chat established!\n");
    time_t lasttime = time(NULL); // 建立连接的时间
    char buf[4096] = {0};
    fd_set rdset;
    while(1){
        FD_ZERO(&rdset);
        FD_SET(fdr,&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        struct timeval tv;
        tv.tv_sec = 1;
        tv.tv_usec = 0;
        select(fdr+1,&rdset,NULL,NULL,&tv);
        time_t now = time(NULL);
        printf("time = %s\n", ctime(&now));
        if(FD_ISSET(fdr,&rdset)){
            lasttime = now; // B发送消息了
            memset(buf,0,sizeof(buf));
            read(fdr,buf,sizeof(buf));
            printf("buf = %s\n", buf);
        }
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            memset(buf,0,sizeof(buf));
            read(STDIN_FILENO,buf,sizeof(buf));
            write(fdw,buf,strlen(buf));
        }
        if(now - lasttime > 10){
            printf("B is disconnected!\n");
            break;
        }
    }
    close(fdw);
    close(fdr);
    return 0;
}

